package com.blocks.mq.listener.receiver;

import com.alibaba.fastjson.JSONObject;
import com.blocks.mq.listener.entity.Student;
import com.blocks.mq.listener.example.service.ExampleTxtWriterService;
import com.blocks.mq.listener.example.service.ExampleXlsxWriterService;
import com.blocks.mq.listener.repository.StudentRepository2;
import com.zut.blocks.base.mq.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: cjc
 * Date: 2020/12/1
 * Time: 10:24
 * Description: No Description
 */
@Component
public class TopicConsumerListener {
    Logger logger = LoggerFactory.getLogger(QueueConsumerListener.class);
    @Autowired
    StudentRepository2 studentRepository2;

    @Autowired
    ExampleXlsxWriterService exws;

    @Autowired
    ExampleTxtWriterService etws;

    //topic模式的消费者
    @JmsListener(destination = "${spring.activemq.topic-name}", containerFactory = "topicListener")
    public void readActiveQueue(String message) {

        System.out.println("topic接受到：" + message);

        Message messages = JSONObject.parseObject(message, Message.class);
        Message.MessageType type = messages.getType();
        if (type == Message.MessageType.str) {
            System.out.println(messages.getData());
            Student student = JSONObject.parseObject(messages.getData(), Student.class);
            System.out.println(student);
            Student s2 = studentRepository2.save(student);
        }
        if (type == Message.MessageType.xlsx) {
            List<List<String>> data = new ArrayList<>();
            String[] strLine = messages.getData().split("\r\n");
            for (String s : strLine) {
                String[] strList = s.split(" ");
                data.add(Arrays.asList(strList));
            }
            exws.writeExcel(data, messages.getFilePath());
            logger.info("excel文件保存成功");
        }
        if (type == Message.MessageType.txt) {
            etws.writeTxt(messages.getData(), messages.getFilePath());
            logger.info("txt文件保存成功");
        }
    }
}